import { OpenAI } from 'openai';
import { KnowledgeService } from '../services/KnowledgeService';
import { closeDatabase } from '../config/database';

// 初始化 OpenAI 客户端
const openai = new OpenAI({
  apiKey: process.env['OPENAI_API_KEY'],
});

// 创建向量嵌入的辅助函数
async function generateEmbedding(text: string): Promise<number[]> {
  const response = await openai.embeddings.create({
    model: 'text-embedding-ada-002',
    input: text,
  });
  if(!response) return [];
  if(!response.data) return [];
  return response.data[0]?.embedding || [];
}

// 使用示例
async function main() {
  const knowledgeService = new KnowledgeService();

  try {
    console.log('🚀 开始演示 PostgreSQL + Drizzle ORM + pgvector 向量搜索');

    // 1. 创建知识条目
    console.log('\n📝 创建知识条目...');
    
    const taskKnowledge = await knowledgeService.createKnowledge({
      content: '如何使用 Drizzle ORM 进行向量相似度搜索',
      knowledgeType: 'task'
    }, generateEmbedding);
    if(!taskKnowledge) return;
    
    const docKnowledge = await knowledgeService.createKnowledge({
      content: 'PostgreSQL pgvector 扩展提供了高效的向量存储和搜索功能',
      knowledgeType: 'document'
    }, generateEmbedding);
    if(!docKnowledge) return;

    const conversationKnowledge = await knowledgeService.createKnowledge({
      content: '用户询问了关于数据库性能优化的最佳实践',
      knowledgeType: 'conversation'
    }, generateEmbedding);
    if(!conversationKnowledge) return;

    console.log(`✅ 创建了 3 个知识条目: ${taskKnowledge.id}, ${docKnowledge.id}, ${conversationKnowledge.id}`);

    // 2. 执行相似度搜索
    console.log('\n🔍 执行向量相似度搜索...');
    
    const searchResults = await knowledgeService.searchSimilar(
      '数据库向量搜索的使用方法',
      generateEmbedding,
      5
    );

    console.log('搜索结果:');
    searchResults.forEach((result, index) => {
      console.log(`${index + 1}. [${result.knowledgeType}] ${result.content} (距离: ${result.distance.toFixed(4)})`);
    });

    // 3. 按类型过滤的相似度搜索
    console.log('\n🎯 按类型过滤的相似度搜索 (仅搜索 task 类型)...');
    
    const taskResults = await knowledgeService.searchSimilarByType(
      'ORM 使用教程',
      'task',
      generateEmbedding,
      3
    );

    console.log('Task 类型搜索结果:');
    taskResults.forEach((result, index) => {
      console.log(`${index + 1}. ${result.content} (距离: ${result.distance.toFixed(4)})`);
    });

    console.log('\n✨ 演示完成！');

  } catch (error) {
    console.error('❌ 发生错误:', error);
  } finally {
    // 优雅关闭数据库连接
    await closeDatabase();
    console.log('🔌 数据库连接已关闭');
  }
}

// 运行示例 (仅在直接执行此文件时运行)
if (import.meta.url === `file://${process.argv[1]}`) {
  main().catch(console.error);
}

export { main as runExample };
